<?php

class UserDAO extends DAO {

    /**
     * 平台ID转用户ID
     * @param type $oid
     * @return type 
     */
    public static function oid2uid($oid = 0)
	{
        if (!$oid) return false;
        
        $uid = 0;
        $mck = "o:{$oid}";
        $mcconf = self::mchash("oid", $oid);
        $ret = self::getcache($oid, $mcconf, $mck, 0, __FUNCTION__);
        if ($ret)
		{
            $uids = !is_array($ret) && strlen($ret) == 4 ? @unpack("N", $ret) : 0;
            if ($uids)
			{
                $u = $uids[1];
                set_global("mc:{$mck}", $u);
                return $u;
            }
        }
        $dbconf = self::dbhash(0, "pvn_global", "idtrans");
        $dbconn = self::getconn(0, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;
        
        $oid = mysql_escape_string($oid);
        $sql = "select uid from {$dbconf[4]} where oid='{$oid}'";
        $uid = self::dbquery($dbconn, $sql, "value");
        self::dbclose($dbconn);
        if (!$uid) return false;
        
        if (self::setcache($uid, $mcconf, $mck, pack("N", $uid), __FUNCTION__)) set_global("mc:{$mck}", $uid);
        
        return $uid;
    }

	public static function oid2uidinfo($oid = 0)
	{
        if (!$oid) return false;
        
        $uid = 0;
        $mck = "oi:{$oid}";
        $mcconf = self::mchash("oid", $oid);
        $ret = self::getcache($oid, $mcconf, $mck, 0, __FUNCTION__);
        if ($ret)
		{
            if (!is_array($ret)) $ret = self::unzbin($ret);
			if($ret)
			{
				set_global("mc:{$mck}", $ret);
				return $ret;
			}
        }
        $dbconf = self::dbhash(0, "pvn_global", "idtrans");
        $dbconn = self::getconn(0, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;
        
        $oid = mysql_escape_string($oid);
        $sql = "select uid, rtm, l0, l1, l2, l3, l4, l5, l6, l7, l15, l30 from {$dbconf[4]} where oid='{$oid}'";
        $row = self::dbquery($dbconn, $sql, "row");
        self::dbclose($dbconn);
        if (!$row) return false;
        
		$bin = self::zbin($row);
        if (self::setcache($uid, $mcconf, $mck, $bin, __FUNCTION__)) set_global("mc:{$mck}", $row);
        
        return $row;
    }

	public static function setrlogin($uid = 0, $loginstat = array())
	{
		if(!$uid || !$loginstat) return false;

		$sets = array();
		foreach($loginstat as $idx => $v)
		{
			if($idx == 'lastlogin' && $v) $sets[] = "ltm=" . time();
			elseif($idx <= 7 && $v) $sets[] = "l{$idx}='1'";
			elseif($idx == 8 && $v) $sets[] = "l15='1'";
			elseif($idx == 9 && $v) $sets[] = "l30='1'";
		}
		if(!$sets) return false;
		$sets = implode(",", $sets);

		$dbconf = self::dbhash(0, "pvn_global", "idtrans");
        $dbconn = self::getconn(0, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;
        
        $oid = mysql_escape_string($oid);
        $sql = "update {$dbconf[4]} set {$sets} where uid='{$uid}'";
        $ret = self::dbquery($dbconn, $sql);
        self::dbclose($dbconn);

		return $ret;
	}

    /**
     * 批量平台ID转用户ID
     * @param type $oids
     * @return boolean 
     */
    public static function oids2uids($oids = array())
	{
        if (!$oids || !is_array($oids)) return false;
        
        $ret = array();
        $dbconf = self::dbhash(0, "pvn_global", "idtrans");
        $dbconn = self::getconn(0, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;
        
        $oidstr = implode("','", $oids);
        $oidstr = "'{$oidstr}'";
        $sql = "select oid, uid from {$dbconf[4]} where oid in ({$oidstr})";
        $res = self::dbquery($dbconn, $sql);
        if ($res && mysql_num_rows($res) >= 1)
		{
            while ($row = mysql_fetch_assoc($res)) $ret[$row["oid"]] = $row['uid'];
            unset($row);
        }
        self::dbclose($dbconn);
        return $ret;
    }

    /**
     * 添加新用户ID
     * @param type $oid
     * @return type 
     */
    public static function newuid($oid = "")
	{
        if (!$oid) return false;
        
		$tm = time();

        $dbconf = self::dbhash(0, "pvn_global", "idtrans");
        $dbconn = self::getconn(0, $dbconf, __FUNCTION__);
        $oid = mysql_escape_string($oid);
        $ret = self::dbquery($dbconn, "insert into {$dbconf[4]} (oid, rtm) values('{$oid}', '{$tm}')");
        if (!$ret)
		{
            self::dbclose($dbconn);
            return false;
        }
        $ret = self::dbid($dbconn);
        self::dbclose($dbconn);
        return $ret;
    }

    /**
     * 获取用户信息
     * @param type $uid
     * @param type $db
     * 出错返回False
     * 无值返回空数组
     * 有值返回oid,name,sex,age,thumb
     */
    public static function getuser($uid = 0, $db = 0)
	{
        $uid = intval($uid);
        if (!$uid) return false;
        
        $mck = "u:{$uid}";
        $mcconf = self::mchash("user", $uid);
        $ret = self::getcache($uid, $mcconf, $mck, $db, __FUNCTION__);
        if ($ret)
		{
            set_global("mc:{$mck}", $ret);
            return $ret;
        }
        $dbconf = self::dbhash($uid, "pvn_user", "user");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;
        
        $sql = "select oid, name, sex, age, thumb from {$dbconf[4]} where uid={$uid}";
        $ret = self::dbquery($dbconn, $sql, "row");
        self::dbclose($dbconn);
        if ($ret === false) return false;
        
        if (self::setcache($uid, $mcconf, $mck, $ret, __FUNCTION__)) set_global("mc:{$mck}", $ret);
        return $ret;
    }

    /**
     * 添加新用户信息
     * @param type $uid
     * @param type $oid
     * @param type $name
     * @param type $thumb
     * @param type $sex
     * @param type $age
     * 出错返回False
     * 正确返回True
     */
    public static function newuser($uid = 0, $oid = "", $name = "", $thumb = "", $sex = 0, $age = 0)
	{
        $uid = intval($uid);
        $sex = intval($sex);
        $age = intval($age);
        $oid = mysql_escape_string($oid);
        $name = mysql_escape_string($name);
        $thumb = mysql_escape_string($thumb);
        if (!$uid || !$oid || !$name) return false;
        
        $dbconf = self::dbhash($uid, "pvn_user", "user");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
        $ret = self::dbquery($dbconn, "insert into {$dbconf[4]} (uid, oid, name, sex, age, thumb) values({$uid}, '{$oid}', '{$name}', '{$sex}', '{$age}', '{$thumb}')");
        self::dbclose($dbconn);
        if (!$ret) return false;
        
        return $ret;
    }

    /**
     * 设置用户信息
     * @param type $uid
     * @param type $name
     * @param type $thumb
     * @param type $sex
     * @param type $age
     * @return type 
     */
    public static function setuser($uid = 0, $name = "", $thumb = "", $sex = 0, $age = 0)
	{
        $uid = intval($uid);
        $sex = intval($sex);
        $age = intval($age);
        $name = mysql_escape_string($name);
        $thumb = mysql_escape_string($thumb);
        if (!$uid || !$name) return false;
        
        $ou = self::getuser($uid);
        if (!$ou) return false;
        
		 $sets = array();
        if ($ou['name'] != $name) $sets[] = "name='{$name}'";
        if ($ou['thumb'] != $thumb) $sets[] = "thumb='{$thumb}'";
        if ($ou['sex'] != $sex) $sets[] = "sex='{$sex}'";
        if ($ou['age'] != $age) $sets[] = "age='{$age}'";
        if (!$sets) return true;

        $sets = implode(",", $sets);
        $mck = "u:{$uid}";
        $mcconf = self::mchash("user", $uid);
        if (!self::delcache($uid, $mcconf, $mck, __FUNCTION__)) return false;

		$dbconf = self::dbhash($uid, "pvn_user", "user");
		$dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
		if (!$dbconn) return false;
		
		$sql = "update {$dbconf[4]} set {$sets} where uid={$uid}";
		$ret = self::dbquery($dbconn, $sql);
		self::dbclose($dbconn);

		return $ret;
    }

    /**
     * 获取用户扩展信息
     * @param type $uid
     * @param type $db
     * @return type 
     */
    public static function getuserext($uid = 0, $db = 0)
	{
        $uid = intval($uid);
        if (!$uid) return false;
        $mck = "un:{$uid}";
        $ret = false;
        $mcconf = self::mchash("userext", $uid);
        $ret = self::getcache($uid, $mcconf, $mck, $db, __FUNCTION__);
        if ($ret)
		{
            if (!is_array($ret))
			{
                $ret = self::unzbin($ret);
            }
            set_global("mc:{$mck}", $ret);
            return $ret;
        }
        $dbconf = self::dbhash($uid, "pvn_userext", "user");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;
        
        $sql = "select * from {$dbconf[4]} where uid={$uid}";
        $ret = self::dbquery($dbconn, $sql, "row");
        self::dbclose($dbconn);
        if ($ret === false) return false;
        
        $bin = self::zbin($ret);
        if (self::setcache($uid, $mcconf, $mck, $bin, __FUNCTION__)) set_global("mc:{$mck}", $ret);
        
        return $ret;
    }

    //添加新用户扩展信息
    public static function newuserext($uid = 0, $data = array())
	{
        $uid = intval($uid);
        if (!$uid || !$data || !is_array($data)) return false;

		$sets = array();
		foreach($data as $k => $v)
		{
			switch($k)
			{
				case 'xp':
				case 'gb':
				case 'mb':
				case 'price':
				case 'nnewoffer':
				case 'nokoffer':
				case 'noffered':
				case 'nfire':
				case 'nokfire':
				case 'nfailfire':
				case 'hfreshtm':
				case 'hnfresh':
				case 'hnpos':
					$v = intval($v);
					$sets[] = "{$k}='{$v}'";
					break;
				case 'side':
				case 'hfresh':
				case 'enemies':
					$v = mysql_escape_string($v);
					$sets[] = "{$k}='{$v}'";
					break;
			}
		}
		if(!$sets) return false;
		$sets[] = "uid='{$uid}'";
		$sets = implode(",", $sets);
        
        $dbconf = self::dbhash($uid, "pvn_userext", "user");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
		if(!$dbconn) return false;

        $ret = self::dbquery($dbconn, "insert into {$dbconf[4]} set {$sets}");
        self::dbclose($dbconn);
        
        return $ret;
    }

	//设置用户扩展信息
    public static function setuserext($uid = 0, $data = array())
	{
        $uid = intval($uid);
		if (!$uid || !$data || !is_array($data)) return false;
    
        $ou = self::getuserext($uid);
        if (!$ou) return false;

		$mck = "un:{$uid}";
        $mcconf = self::mchash("userext", $uid);
        if (!self::delcache($uid, $mcconf, $mck, __FUNCTION__)) return false;
        
        $sets = array();
		foreach($data as $k => $v)
		{
			switch($k)
			{
				case 'xp':
				case 'gb':
				case 'mb':
				case 'price':
				case 'nnewoffer':
				case 'nokoffer':
				case 'noffered':
				case 'nfire':
				case 'nokfire':
				case 'nfailfire':
				case 'hfreshtm':
				case 'hnfresh':
				case 'hnpos':
					$v = intval($v);
					$sets[] = "{$k}='{$v}'";
					break;
				case 'side':
				case 'hfresh':
				case 'enemies':
					$v = mysql_escape_string($v);
					$sets[] = "{$k}='{$v}'";
					break;
			}
		}
		if(!$sets) return false;
		$sets = implode(",", $sets);
        
		$dbconf = self::dbhash($uid, "pvn_userext", "user");
		$dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
		if (!$dbconn) return false;
		
		$sql = "update {$dbconf[4]} set {$sets} where uid={$uid}";
		$ret = self::dbquery($dbconn, $sql);
		self::dbclose($dbconn);
		
		return $ret;
    }

    /**
     * 初始化用户信息
     * @param type $uid
     * @param type $db
     * @return type 
     */
    public static function setinit($uid = 0)
	{
        $uid = intval($uid);
        if (!$uid)  return false;
        
        $uconfig = &load_conf("pub:newuser");    
		$uxp = intval($uconfig['user']['xp']);
		$ugb = intval($uconfig['user']['gb']);
		$umb = intval($uconfig['user']['mb']);
		if(!self::setuserext($uid, array(
			'xp'	=> $uxp,
			'gb'	=> $ugb,
			'mb'	=> $umb
		))) return false;
        
        unset($mck, $mcconf, $dbconf, $dbconn);

        //TODO: 初始化用户其他数据

        return true;
    }

	public static function logmb($uid = 0, $msg = "")
	{
		//TODO: log mb
	}

	//clearuser之前必须先clearuid
	public static function clearuser($uid = 0)
	{
		$uid = intval($uid);
        if (!$uid)  return false;

		if(self::getuser($uid) === false) return false;

		$mcconf = self::mchash("user", $uid);
        if (!self::delcache($uid, $mcconf, "u:{$uid}", __FUNCTION__)) return false;

		$dbconf = self::dbhash($uid, "pvn_user", "user");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;

		$sql = "delete from {$dbconf[4]} where uid='{$uid}'";
		$ret = self::dbquery($dbconn, $sql);
		self::dbclose($dbconn);

		return $ret;
	}

	public static function clearuserext($uid = 0)
	{
		$uid = intval($uid);
        if (!$uid)  return false;

		if(self::getuserext($uid) === false) return false;

		$mcconf = self::mchash("userext", $uid);
        if (!self::delcache($uid, $mcconf, "un:{$uid}", __FUNCTION__)) return false;

		$dbconf = self::dbhash($uid, "pvn_userext", "user");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;

		$sql = "delete from {$dbconf[4]} where uid='{$uid}'";
		$ret = self::dbquery($dbconn, $sql);
		self::dbclose($dbconn);

		return $ret;
	}

	public static function clearuid($uid = 0)
	{
		$uid = intval($uid);
        if (!$uid)  return false;

		$user = self::getuser($uid);
		if($user === false) return false;

		$oid = $user['oid'];

		$mcconf = self::mchash("oid", $uid);
        if (!self::delcache($uid, $mcconf, array("o:{$oid}", "oi:{$oid}"), __FUNCTION__)) return false;

		$dbconf = self::dbhash($uid, "pvn_global", "idtrans");
        $dbconn = self::getconn($uid, $dbconf, __FUNCTION__);
        if (!$dbconn) return false;

		$sql = "delete from {$dbconf[4]} where oid='{$oid}'";
		$ret = self::dbquery($dbconn, $sql);
		self::dbclose($dbconn);

		return $ret;
	}

	public static function setusermsg($uid = 0, $type = 0, $data = array())
	{
        $uid = intval($uid);
        $type = intval($type);
        if (!$uid || !$type) return false;

        $mck = "umsg:{$uid}:{$type}";
        $ret = false;
        $mcconf = self::mchash("user", $uid);
        $ret = self::getcache($uid, $mcconf, $mck, 0, __FUNCTION__);
        if ($ret)
		{
            if (!is_array($ret))
			{
                $ret = self::unzbin($ret);
            }
        }

		$ret = $ret ? $ret : array();
		switch($type)
		{
			case 10: //写用户悬赏通知，接受用户显示
			case 11: //写用户悬赏通知，发起用户显示
			case 12: //写用户悬赏通知，被悬赏用户显示
			case 20: //写用户悬赏重发通知
				$data["uid"] = intval($data["uid"]);
				$data["tuid"] = intval($data["tuid"]);
				if(!$data["uid"] || !$data["tuid"]) return false;

				$k = "{$data["uid"]}:{$data["tuid"]}";
				$ret[$k] = $type;
				break;
		}
        
        $bin = self::zbin($ret);
        return self::setcache($uid, $mcconf, $mck, $bin, __FUNCTION__);
    }

	public static function getusermsg($uid = 0, $type = 0)
	{
        $uid = intval($uid);
        $type = intval($type);
        if (!$uid || !$type) return false;

        $mck = "umsg:{$uid}:{$type}";
        $ret = false;
        $mcconf = self::mchash("user", $uid);
        $ret = self::getcache($uid, $mcconf, $mck, 0, __FUNCTION__);
        if ($ret)
		{
            if (!is_array($ret))
			{
                $ret = self::unzbin($ret);
            }
        }

		return $ret;
    }
}
?>